package bTree.LeetCode;

public class 买卖股票的最佳时机4 {
    public int maxProfit(int k, int[] prices) {
        int length = prices.length;
        int[][] dp = new int[length][k * 2 + 1];
        int x = 1;
        //初始化
        for (int i = 1; i <= k; i++) {
            dp[0][x] = -prices[0];
            x += 2;
        }
        for (int i = 1; i < length; i++) {
//            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
//            dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
//            dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
//            dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
            for (int j = 1; j <= k * 2; j++) {
                if (j % 2 == 1) {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]);

                }
            }
        }
        return dp[length-1][k*2];
    }
}